//
//  HotTikctView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/19.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class HotTikctView: UIView {
    
    // 按钮图片个数
    private let picsCount = 4
    // 存放按钮图片
    private lazy var btns = [UIImageView]()
    // 显示图片城市
    private lazy var cities = ["北京","天津","西安","重庆"]
    
    // 回调
    public var complete: ((_ item:Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        init_views()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        let bigH = frame.height * 0.65
        let smallH = frame.height - bigH - MARGIN10 * 3
        let bigW = (frame.width - MARGIN * 2 - MARGIN10) * 0.5
        // 第一张图片
        let btn1 = btns[0]
        btn1.frame = CGRect(x: MARGIN, y: 0, width: bigW, height: bigH)
        addSubview(btn1)
        // 第二张图片
        let btn2 = btns[1]
        btn2.frame = CGRect(x: MARGIN, y: btn1.frame.maxY + MARGIN10, width: bigW, height: smallH)
        addSubview(btn2)
        // 第三张图片
        let btn3 = btns[2]
        btn3.frame = CGRect(x: btn1.frame.maxX + MARGIN10, y: 0, width: bigW, height: smallH)
        addSubview(btn3)
        // 第四张图片
        let btn4 = btns[3]
        btn4.frame = CGRect(x: btn1.frame.maxX + MARGIN10, y: btn3.frame.maxY + MARGIN10, width: bigW, height: bigH)
        addSubview(btn4)
    }
}

extension HotTikctView {
    
    private func init_views() -> Void {
        for i in 0..<picsCount {
            let btn = UIImageView()
            btn.tag = i
            btn.contentMode = .scaleAspectFill
            btn.isUserInteractionEnabled = true
            btn.image = UIImage(named: "hot\(i)")
            // 圆角图片
            btn.layer.cornerRadius = 5
            btn.layer.masksToBounds = true
            // 地标城市
            let label = UILabel(title: cities[i])
            label.textColor = UIColor.white
            label.font = UIFont.systemFont(ofSize: 13)
            label.frame = CGRect(x: MARGIN10, y: 0, width: MARGIN * 2, height: MARGIN * 2)
            // 添加到父控件
            btn.addSubview(label)
            // 存放按钮图片
            btns.append(btn)
            // 添加按钮点击事件
            btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickItem(btn:))))
        }
    }
    
    @objc func clickItem(btn:UITapGestureRecognizer) {
        if let callback = complete ,let index = btn.view?.tag{
            callback(index)
        }
    }
}
